﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileEncryption
{
    class FileEncryption
    {
        public static string inputFile = "../../example.bin";
        private const int BUFFER_SIZE = 5;

        static void Main()
        {
            EncryptFile();
            DecryptFile();
        }

        private static void EncryptFile()
        {
            FileStream fs = new FileStream(inputFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            using (fs)
            {
                byte[] buf = new byte[BUFFER_SIZE];
                while (true)
                {
                    int bytesRead = fs.Read(buf, 0, buf.Length);
                    if (bytesRead == 0)
                    {
                        // End of file reached
                        break;
                    }
                    buf = RotateBytes(buf);
                    fs.Seek(-bytesRead, SeekOrigin.Current);
                    fs.Write(buf, 0, bytesRead);
                }
            }
        }

        private static byte[] RotateBytes(byte[] buf)
        {
            byte[] rotatedbuf = new byte[buf.Length];
            for (int i = 0; i < buf.Length; i++)
            {
                rotatedbuf[(i + 1) % buf.Length] = buf[i];
            }
            return rotatedbuf;
        }

        private static void DecryptFile()
        {
            FileStream fs = new FileStream(inputFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            using (fs)
            {
                byte[] buf = new byte[BUFFER_SIZE];
                while (true)
                {
                    int bytesRead = fs.Read(buf, 0, buf.Length);
                    if (bytesRead == 0)
                    {
                        // End of file reached
                        break;
                    }
                    buf = RotateBytesBackwards(buf);
                    fs.Seek(-bytesRead, SeekOrigin.Current);
                    fs.Write(buf, 0, bytesRead);
                }
            }
        }

        private static byte[] RotateBytesBackwards(byte[] buf)
        {
            byte[] rotatedbuf = new byte[buf.Length];
            for (int i = 0; i < buf.Length; i++)
            {
                rotatedbuf[(i + buf.Length - 1) % buf.Length] = buf[i];
            }
            return rotatedbuf;
        }
    }
}
